﻿using System.Collections;
using UnityEngine;

namespace CGF
{
    public class CameraHelper : MonoBehaviour
    {
        public static async CTask<Texture2D> GetRenderFrame(Camera camera)
        {
            GameObject go = new GameObject(nameof(CameraHelper));
            var mono = go.AddComponent<CameraHelper>();
            CTask<Texture2D> task = CTask<Texture2D>.Create();
            mono.StartCoroutine(mono.CaptureCamera(task, camera, (int)ScreenHelper.screenUISize.x, (int)ScreenHelper.screenUISize.y));
            return await task;
        }

        private IEnumerator CaptureCamera(CTask<Texture2D> task, Camera camera, int width, int height)
        {
            yield return new WaitForEndOfFrame();
            RenderTexture renderTexture = new RenderTexture(width, height, 24, RenderTextureFormat.ARGB32);
            camera.targetTexture = renderTexture;
            camera.Render();
            RenderTexture.active = renderTexture;
            Texture2D texture = new Texture2D(width, height, TextureFormat.RGBA32, false);
            texture.ReadPixels(new Rect(0, 0, width, height), 0, 0);
            texture.Apply();
            camera.targetTexture = null;
            RenderTexture.active = null;
            Destroy(renderTexture);
            Destroy(gameObject);
            task.SetResult(texture);
        }
    }
}